const PubSub = {
  id:1,
  callbacks:{
    // pay:{
    //   token_1:fn,
    //   token_2:fn2
    // }
  }
}

PubSub.subscribe = function(channel,callback){
  let token = "token_" + this.id++;
  if(this.callbacks[channel]){
    this.callbacks[channel][token] = callback
  }else{
    this.callbacks[channel] = {
      [token]:callback
    }
  }
  return token
}

PubSub.publish = function(channel,data){
  if(this.callbacks[channel]){
    Object.values(this.callbacks[channel]).forEach(callback=>{
      callback(data)
    })
  }
}

//取消消息订阅
// 1.没有传值，flag为undefined
// 2.传入token字符串
// 3.msgName字符串
PubSub.unsubscribe = function(flag){
  if(flag === undefined){
    this.callbacks = {}
  }else if(typeof flag === 'string'){
    // 判断是否为token_开发
    if(flag.indexOf('token_') === 0){
      // 表明是一个订阅id
      let callbackObj = Object.values(this.callbacks).find(obj => obj.hasOwnProperty(flag))
      if(callbackObj){
        delete callbackObj[flag]
      }
    }else{
      // 表明是一个频道的名称
      delete this.callbacks[flag]
    }
  }
}